<template>
  <el-row style="height:100%">
    <page @buttons="configPermissions">
      <pageheader :event="'openingPopUp'" :isShow="buttonPermissions.isAdd">
        营业时间管理
      </pageheader>
      <div class="page-content">
        <el-card class="box-card">
          <el-row style="margin-bottom: 20px">
            <Cascader
              :value.sync="company_id_arr"
              :options.sync="options"
              :width="'300px'"
              :changeEvent="'openingChange'"
            >所属企业：
            </Cascader>
          </el-row>
          <el-table :data="dataTable" size="small" stripe>
            <el-table-column label="序号" type="index" :index="indexMethod" align="center" width="60"></el-table-column>
            <el-table-column label="营业时间名称" prop="name" align="center"></el-table-column>
            <el-table-column label="营业时间描述" prop="info" align="center"></el-table-column>
            <el-table-column label="是否是公共营业时间" prop="is_common" align="center">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.is_common  == 1" size="mini" type="success">是</el-tag>
                <el-tag v-else size="mini" type="danger">否</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="是否是父级营业时间" prop="is_parent" align="center">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.is_parent  == 1" size="mini" type="success">是</el-tag>
                <el-tag v-else size="mini" type="danger">否</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="right" header-align="center" width="320">
              <template slot-scope="scope">
                <el-button @click="bindArea(scope.row)" v-if="scope.row.is_common == 0" type="success" size="small">绑定区域</el-button>
                <el-button @click="copy(scope.row)" type="primary" size="small">复制</el-button>
                <el-button v-if="scope.row.is_common == 0 || buttonPermissions.isRoot"
                  @click="openingData(scope.row)" size="small">详情</el-button>
                <el-button v-if="scope.row.is_common == 0 || buttonPermissions.isRoot"
                  type="danger" @click="openingDel(scope.row)"  size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <!--新增模态框-->
        <el-dialog v-dialogDrag :title="pageTitle" :visible.sync="isShow" width="1200px" @opened="openedDialog(company_id)" @close="closeDialog"
                   :modal-append-to-body="false" :close-on-click-modal="false" top="12vh">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="180px">
            <el-form-item label="所属企业" prop="company_id_arr">
              <Cascader :value.sync="ruleForm.company_id_arr"
                        :options="options"
                        :changeEvent="'companyChange'"
                        :width="'450px'"
                        :disabled="isDisabled"
                        :isClearable="false"></Cascader>
            </el-form-item>
            <el-form-item label="名称" prop="name">
              <el-input v-model="ruleForm.name" size="small" style="width:450px"></el-input>
            </el-form-item>
            <el-form-item label="描述" prop="info">
              <el-input v-model="ruleForm.info" type="textarea" size="small" style="width:450px" maxlength="20"></el-input>
            </el-form-item>
            <el-form-item label="新增营业时间条目" v-if="!is_common">
              <el-button type="primary" @click="isShowItem=true" size="small">新增</el-button>
            </el-form-item>
            <el-form-item label="营业时间列表" prop="item_list">
              <el-table id="isItemListTable" :data="ruleForm.item_list" :row-key="getRowKeys">
                <el-table-column align="center" width="60px">
                  <template slot="header" :slot-scope="'slot'">
                    <el-popover placement="right-start" title="说明:" width="200" trigger="hover"
                                content="拖拽进行排序">
                      <i slot="reference" class="el-icon-question"></i>
                    </el-popover>
                  </template>
                  <template slot-scope="scope">
                    <i slot="reference" class="el-icon-sort"></i>
                    {{scope.row.level}}
                  </template>
                </el-table-column>
                <el-table-column label="描述" prop="info" align="center"></el-table-column>
                <el-table-column label="是否是假日" prop="is_holiday" align="center">
                  <template slot-scope="scope">
                    <el-tag v-if="scope.row.is_holiday == 1" size="mini" type="success">是</el-tag>
                    <el-tag v-else size="mini" type="danger">否</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="开始日期" prop="start_day" align="center"></el-table-column>
                <el-table-column label="结束日期" prop="end_day" align="center"></el-table-column>
                <el-table-column label="营业时间" prop="open_time" align="center"></el-table-column>
                <el-table-column label="结束时间" prop="close_time" align="center">
                  <template slot-scope="scope">
                    <span v-if="scope.row.close_time_next">{{scope.row.close_time_next}}</span>
                    <span v-else>{{scope.row.close_time}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="星期" prop="weeks" align="center"></el-table-column>
                <el-table-column label="操作" align="center" width="160px">
                  <template slot-scope="scope">
                    <el-button @click="itemListShow(scope.row.id)" size="small">详情</el-button>
                    <el-button @click="itemListDelete(scope.row.id)" size="small" type="danger">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-form>
          <el-dialog  v-dialogDrag title="添加营业时间" :visible.sync="isShowItem"
                      @opened="openedItemList"
                      @close="closeItemList"
                      width="900px" append-to-body
                      :close-on-click-modal=false>
            <el-form :model="ruleFormItmeList" :rules="rulesItemList" ref="ruleFormItemList" label-width="180px">
              <el-form-item label="描述：" prop="info">
                <el-input v-model="ruleFormItmeList.info" size="small" style="width:450px"></el-input>
              </el-form-item>
              <el-form-item label="是否是假日：" prop="is_holiday">
                <el-switch
                  v-model="ruleFormItmeList.is_holiday"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="是"
                  inactive-text="否"
                  active-value="1"
                  inactive-value="0">
                </el-switch>
              </el-form-item>
              <el-form-item label="选择日期：" prop="days">
                <el-select v-model="startM" placeholder="月" size="mini" @change="startMchange" style="width: 60px;">
                  <el-option v-for="item in MonList"
                    :key="item" :label="item" :value="item"></el-option>
                </el-select>
                <span>月 -</span>
                <el-select v-model="startD" placeholder="日" size="mini" style="width: 60px;">
                  <el-option v-for="item in startDayList"
                             :key="item"
                             :label="item"
                             :value="item"></el-option>
                </el-select>
                <span>日</span>
                <span style="margin: 0 20px">至</span>
                <el-select v-model="endM" placeholder="月" size="mini" @change="endMchange" style="width: 60px;">
                  <el-option v-for="item in MonList"
                             :key="item" :label="item" :value="item"></el-option>
                </el-select>
                <span>月 -</span>
                <el-select v-model="endD" placeholder="日" size="mini" style="width: 60px;">
                  <el-option v-for="item in endDayList"
                             :key="item"
                             :label="item"
                             :value="item"></el-option>
                </el-select>
                <span>日</span>
              </el-form-item>
              <el-form-item label="营业时间：" prop="open_time">
                <el-time-select
                  placeholder="营业时间"
                  v-model="ruleFormItmeList.open_time"
                  :picker-options="{
                    start: '00:00',
                    step: '00:10',
                    end: '24:00'
                  }"
                  value-format="HH:mm"
                  format="HH:mm"
                  size="small"
                  style="width: 450px">
                </el-time-select>
              </el-form-item>
              <el-form-item label="结束时间：" prop="close_time">
                <el-time-select
                  placeholder="结束时间"
                  v-model="ruleFormItmeList.close_time"
                  :picker-options="{
                    start: '00:00',
                    step: '00:10',
                    end: '24:00'
                  }"
                  value-format="HH:mm"
                  format="HH:mm"
                  size="small"
                  style="width: 450px">
                </el-time-select>
                <el-popover placement="right-start" title="说明:" width="300" trigger="hover"
                            content="结束时间早于营业时间时，则为次日">
                  <i slot="reference" class="el-icon-question"></i>
                </el-popover>
              </el-form-item>
              <el-form-item label="星期选择" prop="weeksArr">
                <el-checkbox-group v-model="ruleFormItmeList.weeksArr" size="small">
                  <el-checkbox label="1">星期一</el-checkbox>
                  <el-checkbox label="2">星期二</el-checkbox>
                  <el-checkbox label="3">星期三</el-checkbox>
                  <el-checkbox label="4">星期四</el-checkbox>
                  <el-checkbox label="5">星期五</el-checkbox>
                  <el-checkbox label="6">星期六</el-checkbox>
                  <el-checkbox label="7">星期日</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="isShowItem = false" size="small">取 消</el-button>
              <el-button type="primary" @click="addItemList" size="small">保 存</el-button>
            </div>
          </el-dialog>
          <div slot="footer" class="dialog-footer">
            <el-button @click="isShow = false" size="small">取 消</el-button>
            <el-button v-if="!isDisabled || (!is_common && !is_parent)"
              type="primary" @click="confirmDialog" size="small">保 存</el-button>
          </div>
        </el-dialog>
        <!--绑定区域模态框-->
        <el-dialog v-dialogDrag :title="'绑定区域'" class="bindareadia" @close="bindClose"
         :visible.sync="bindShow" width="1300px" :modal-append-to-body="false" :close-on-click-modal="false" >
          <el-row style="border-bottom:1px solid #dcdcdc;padding-bottom:20px">
             <Cascader
                :value="quyuqiyeId"
                :options="options"
                :width="'220px'"
                :disabled="true"
              >所属企业：
            </Cascader>
            <span style="margin-left:30px;" >选择案场：</span>
            <el-select v-model="submitCase"  @change="CaseChange" @remove-tag="CasetagClick" @visible-change="CaseVisibleChange"  filterable
                   :multiple="true" size="small" collapse-tags placeholder="请选择位置" style="width:300px;">
              <el-option
                v-for="item in Case"
                :key="item.id"
                :label="item.case_name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-row>
          <div style="margin-top:15px;"></div>
            <el-col  :span="11">
              <div class="clear">
                <h3 style="margin:5px 0 15px;float:left;">{{gzTimeName+'当前挂载区域'}}</h3>
                <div class="areasearch-Box" style="margin-right:20px;"><span @click="allDel" >全部删除</span></div>
              </div>
              <el-table stripe  border :data="bindAreaData"   style="width: 100%" 
              size="small" :header-cell-style="{background:'rgb(248,245,254)'}"
                height="350">
                <el-table-column prop="area_name" align="center" label="区域名称" ></el-table-column>
              <el-table-column prop="case_info_name" align="center" label="所属案场" ></el-table-column>
                <el-table-column label="操作" align="center" width="100px">
                  <template slot-scope="scope">
                    <el-button type="text" style="padding: 0;" @click="delBind(scope.row)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <span style="color:rgb(241, 102, 102)">保存后，所选挂载在当前营业时间下的区域将会覆盖之前挂载的营业时间！</span>
            </el-col>
            <el-col :offset="1" :span="11">
              <div class="clear">
               <h3 style="margin:5px 0 15px;float:left;">所有区域</h3>
                 <div class="areasearch-Box" >
                    <el-input   placeholder="请输入关键字" class="table-search"  v-model="areaTableSearch">
                      <i slot="prefix" class="el-input__icon el-icon-search"></i>
                    </el-input>
                  </div>
               </div>
               <el-table 
                @select="areaTableSeleteChange" class="areaT" @select-all="allChange" ref="areaTable" v-loading.lock="tableLoading"
              :data="areaTables"  :header-cell-style="{background:'rgb(248,245,254)'}"
              size="small" border  stripe  height="350" >
              <el-table-column type="selection" prop="area_id" align="center"   width="50"></el-table-column>
              <el-table-column prop="area_name" label="区域名称" align="center" ></el-table-column>
              <el-table-column prop="case_info_name" label="所属案场"  align="center" ></el-table-column>
            </el-table>
            </el-col>
            <div slot="footer" class="dialog-footer">
              <el-button size="small" @click="bindShow = false" >取 消</el-button>
              <el-button size="small" type="primary" @click="saveAreaTime" >保存</el-button>
            </div>
        </el-dialog>
      </div>
    </page>
  </el-row>
</template>

<script>
  import page from "@/components/page/page";
  import pageheader from "@/components/page/pageheader";
  import Cascader from "@/components/sys/assembly/elcascader";
  let moment = require("moment");
  import Sortable from 'sortablejs'
  export default {
    data() {
      let weeksArrValidator = (rule, value, callback) =>{
        if(value.length == 0){
          callback(new Error('至少选择一个'));
        }else{
          callback();
        }
      };
      return {
        pickerOptions: {                //时间日期控件规则
          disabledDate(time) {
            let date = new Date()
            let nowYear = date.getFullYear()
            return time.getTime() > new Date(nowYear,11,31).getTime() || time.getTime() < new Date(nowYear,0,1).getTime();   //正常 今天之前
          },
        },
        tableLoading:false, //区域表格loading
        areaTableSearch:'', //区域表格搜索
        bindShow:false,   //绑定区域模态框
        nowTimeId:'',   //当前选择的时间id
        gzTimeName:'',    //当前点击的营业时间名
        submitCase:[],  //已选案场
        Case:[],        //案场列表
        quyuqiyeId:[],  //当前营业时间所属企业
        isAllCase:false,  //是否选中所有案场
        areaData:[],    //区域列表
        bindAreaData:[], //已关联或选中关联的区域列表
        areaTableCheck:[], //已选表格

        isShow: false,
        isShowItem: false,
        isDisabled: false,
        is_common:false,
        is_parent:false,
        defaultList:[], //默认基础数据
        dataTable: [], //表格数据
        options:[],  //级联控件 所属上级菜单
        company_id_arr:[], //所属企业id arr
        company_id:[], //所属企业id
        keywords:'', //关键字搜索
        ruleForm: {
          company_id:'',//所属企业id
          company_id_arr:'',//所属企业id arr
          name :'',//名称
          info  :'',//描述
          item_list:[],//控制权限 ID list
        },
        rules: {
          company_id_arr: [{ required: true, message: "请选择所属企业",trigger:'change'}],
          name: [{ required: true, message: "请选择名称",trigger:'blur'}],
          item_list:[{ required: true, message: "请至少新增一个营业时间条目",trigger:'change'}],
        },
        ruleFormItmeList:{
          is_holiday: '0',
          days: '',
          weeksArr: ['1','2','3','4','5','6','7'],
          open_time:'',//营业时间
          close_time:'',//结束时间
          info: "",//描述
        },
        rulesItemList:{
          weeksArr:[{ required: true, validator: weeksArrValidator ,trigger:'change'}],
          open_time:[{ required: true, message: "请选择营业时间",trigger:'change'}],
          close_time:[{ required: true, message: "请选择结束时间",trigger:'change'}],
        },
        pageTitle:'新增营业时间',//模态框名称
        buttonPermissions:{
          isAdd:false,
          isDel:false,
          isModify:false,
          isWatch:false,
          isUse:false,
          isReset:false,
          isRoot:false,
        },
        ItemListId:'',//新增营业时间id
        startM:'',
        startD:'',
        startDayList:[],
        endM:'',
        endD:'',
        endDayList:[],
        MonList:["01","02","03","04","05","06","07","08","09","10","11","12"],

        DayList1:["01","02","03","04","05","06","07","08","09","10",
          "11","12","13","14","15","16","17","18","19","20",
          "21","22","23","24","25","26","27","28","29","30",'31'],
        DayList2:["01","02","03","04","05","06","07","08","09","10",
          "11","12","13","14","15","16","17","18","19","20",
          "21","22","23","24","25","26","27","28","29","30"],
        DayList3:["01","02","03","04","05","06","07","08","09","10",
          "11","12","13","14","15","16","17","18","19","20",
          "21","22","23","24","25","26","27","28"],
      }
    },
    inject: ["reload"],
    components: {
      page,
      pageheader,
      Cascader,
    },
    computed:{
      areaTables: function () {
        let search = this.areaTableSearch;
        if (search) {
          return this.areaData.filter(function (dataNews) {
            return Object.keys(dataNews).some(function (key) {
              return String(dataNews[key]).toLowerCase().indexOf(search) > -1
            })
          })
        };
        
        return this.areaData;
      }
    },
    watch: {
      areaTableSearch(val){
        this.areaTableCheck=[];
        this.$nextTick(()=>{
          if (this.bindAreaData && this.bindAreaData.length > 0) {
            this.bindAreaData.forEach((ms,msIndex) => {
              for (let i = 0; i < this.areaData.length; i++) {
                const el = this.areaData[i];
                if(ms.area_id==el.area_id){
                  this.areaTableCheck.push(el);
                  this.$refs.areaTable.toggleRowSelection(el, true);
                }
              }
            });
          };
        })
      }
    },
    created(){
      //判断是否有按钮权限
      if (sessionStorage.buttonPermissions) {
        this.configPermissions(JSON.parse(sessionStorage.buttonPermissions))
      }
      if(localStorage.isRoot){
        this.buttonPermissions.isRoot = localStorage.isRoot == 1 ? true :false
      }
    },
    mounted(){
      this.getTree()
      this.$Bus.$on('openingPopUp',() => {
        this.isShow = true;
        this.isDisabled = false;
        this.is_common = false
      })
      this.$Bus.$on('openingChange', data => {
        this.$Bus.$emit('Loading', true)
        this.company_id_arr=data;
        this.company_id = data.slice(-1)[0];
        this.keywords = ''
        this.getOpeningList(this.company_id)
      })
      this.$Bus.$on('companyChange', data => {
        this.ruleForm.company_id_arr = data;
        this.ruleForm.company_id = data.slice(-1)[0]
        this.ruleForm.org_auth_id_list = []
        this.ruleForm.role_id_list = []
        this.ruleForm.org_auth_id_name = ''
        this.ruleForm.role_id_name = ''
        this.startM = ''
        this.startD = ''
        this.endM = ''
        this.endD = ''
        this.$refs.ruleForm.validateField('company_id_arr');//触发form表单中校验所属企业是否选择
      })
    },
    beforeDestroy(){
      this.$Bus.$off("openingPopUp");
      this.$Bus.$off("openingChange");
      this.$Bus.$off("companyChange");
    },
    methods:{
      //表格序号显示方法
      indexMethod(index){
        return index + 1
      },
      //配置按钮权限，根据权限不同调整表头渲染参数
      configPermissions(val){
        let buttonPermissions = val
        let menuButtonPermissions = [];//按钮权限数组
        buttonPermissions.forEach(e =>{
          for(let key in e){
            if(key == 'menu_code'){
              menuButtonPermissions.push(e[key])
            }
          }
        });
        this.buttonPermissions.isAdd = menuButtonPermissions.includes('userAdd') ? true : false; //是否有新增权限
        this.buttonPermissions.isReset = menuButtonPermissions.includes('userReset') ? true : false; //是否有重置密码权限
      },
      //获取企业tree
      getTree(){
        let url = '/sys/report_assist_new/company_tree';
        this.$api.get(url)
        .then(data => {
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading',false);
            return
          }
          if(data){
            this.company_id_arr = [];
            recursion(data.data);
            function recursion(val) {
              if(val.length){
                for(let i in val){
                  val[i].value = val[i].id;
                  val[i].label = val[i].company_name;
                  val[i].parent_id_str = val[i].parent_name_list.join('/');
                  if(val[i].children && val[i].children.length){
                    recursion(val[i].children)
                  }else{
                    delete val[i].children
                  }
                }
              }
            }
            this.options = data.data;
            this.company_id_arr.push(data.data[0].id);
            this.company_id = data.data[0].id;
            this.getOpeningList(this.company_id)
          }
          this.$Bus.$emit('Loading',false)
        })
        .catch(err=>{
           console.log(err);
          this.$Bus.$emit('Loading',false)
        })
      },
      //获取营业时间列表
      getOpeningList(company_id = ''){
        let url = '/sys/opening_hours/list?company_id='+ company_id
        this.$api.get(url)
        .then(data=>{
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading',false);
            return
          }
          // console.log(data);
          if(data){
            let _data = data.data
            this.dataTable = _data
          }else{
            this.dataTable = []
          }
          this.$Bus.$emit('Loading',false)
        })
        .catch(err=>{
           console.log(err);
          this.dataTable = [];
          this.$Bus.$emit('Loading',false)
        })
      },
      //点击详情
      openingData(data){
        this.isShow = true;
        this.isDisabled = true;
        this.is_common = data.is_common ? true : false
        this.is_parent = data.is_parent ? true : false
        this.pageTitle = '查看营业时间'
        this.ruleForm.company_id = data.id
        this.ruleForm.company_id_arr = [data.id]
        this.$Bus.$emit('Loading',true)
        this.getOpening(data.id)
      },
      //点击删除
      openingDel(data){
        this.$confirm("是否删除‘"+ data.name +"’？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true
        })
        .then(() => {
          this.$Bus.$emit('Loading',true)
          this.delData(data.id);
        })
        .catch(()=>{})
      },
      delData(id){
        let url = "/sys/opening_hours/delete";
        let data = {
          id:id
        }
        this.$api.delete(url,data)
        .then(data => {
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading',false);
            return
          }
          if(data){
            this.getOpeningList(this.company_id)
            this.$message({
              message: "删除成功",
              type: "success"
            });
          }
        })
        .catch(err=>{
           console.log(err);
          this.$Bus.$emit('Loading',false)
        })
      },
      //点击复制
      copy(data){
        // console.log(data);
        this.isShow = true;
        this.isDisabled = false;
        this.is_common = false
        this.getOpening(data.id)
      },
      //根据id获取营业时间参数
      getOpening(id){
        let url = '/sys/opening_hours/get?id='+ id
        this.$api.get(url)
        .then(data=>{
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading',false);
            return
          }
          // console.log(data);
          if(data){
            let _data = data.data
            _data.company_id_arr = _data.node_location ? _data.node_location.split('-'): ''
            if(_data.company_id_arr) _data.company_id_arr.pop();//删除最后一个空元素
            _data.item_list.map( (x,i)=>{
              x.days = [x.start_day,x.end_day]
              x.weeksArr = x.weeks.split(',')
              x.level = x.level ? x.level : (i+1)
            })
            this.ruleForm = _data
            //加入排序
            if (this.ruleForm.item_list && this.ruleForm.item_list.length > 0) {
              for (let i = 0; i < this.ruleForm.item_list.length; i++) {
                this.$set(this.ruleForm.item_list[i], 'level', i+1);
              }
            }
          }
          this.$Bus.$emit('Loading',false)
        })
        .catch(err=>{
           console.log(err);
          this.$Bus.$emit('Loading',false)
        })
      },

      // 一级模态框
      //关闭模态框
      closeDialog(){
        this.pageTitle = '新增营业时间'
        this.$refs.ruleForm.resetFields()
      },
      //一级模态框保存按钮
      confirmDialog(){
        let data = {}
        this.$refs.ruleForm.validate(valid =>{
          if(valid){
            let model = this.$refs.ruleForm.model;
            // 是否是修改
            if(this.isDisabled){
              data.info = model.info;
              data.item_list = model.item_list
              data.name = model.name
              // console.log(data);
              let url = '/sys/opening_hours/update?id=' + this.ruleForm.id
              this.$Bus.$emit('Loading',true)
              this.$api.put(url,data)
              .then(data=>{
                if(data == '10001'){
                  this.$message.error('无权操作该数据')
                  this.$Bus.$emit('Loading',false);
                  return
                }
                // console.log(data);
                if(data){
                  this.$message({
                    message: "保存成功",
                    type: "success"
                  });
                  this.getOpeningList(this.company_id)
                  this.isShow = false
                }
                this.$Bus.$emit('Loading',false)
              })
              .catch(err=>{
                 console.log(err);
                this.$Bus.$emit('Loading',false)
              })
            }else{
              data.company_id = model.company_id_arr.slice(-1)[0]
              data.info = model.info;
              data.item_list = model.item_list
              data.name = model.name
              // console.log(data);
              let url = '/sys/opening_hours/add'
              this.$Bus.$emit('Loading',true)
              this.$api.post(url,data)
              .then(data=>{
                if(data == '10001'){
                  this.$message.error('无权操作该数据')
                  this.$Bus.$emit('Loading',false);
                  return
                }
                // console.log(data);
                if(data){
                  this.$message({
                    message: "保存成功",
                    type: "success"
                  });
                  this.getOpeningList(this.company_id)
                  this.isShow = false
                }
                this.$Bus.$emit('Loading',false)
              })
              .catch(err=>{
                 console.log(err);
                this.$Bus.$emit('Loading',false)
              })
            }
          }
        })
      },
      //显示详情按钮
      itemListShow(id){
        this.isShowItem = true;
        this.ItemListId = id;
      },
      //已经打开添加营业时间
      openedItemList(){
        if(this.ItemListId){
          this.$nextTick(()=>{
            for(let i in this.ruleForm.item_list){
              if(this.ruleForm.item_list[i].id == this.ItemListId){
                this.ruleFormItmeList = JSON.parse(JSON.stringify(this.ruleForm.item_list[i]))//深拷贝，方式原数据被污染
                // console.log(this.ruleFormItmeList,'ruleFormItmeList');
                this.startM = this.ruleFormItmeList.days[0].split('-')[0]
                this.startD =this.ruleFormItmeList.days[0].split('-')[1]
                this.endM = this.ruleFormItmeList.days[1].split('-')[0]
                this.endD =this.ruleFormItmeList.days[1].split('-')[1]
                this.startMchange(this.startM)
                this.endMchange(this.endM)
              }
            }
          })
        }
      },
      //行拖拽
      rowDrop() {
        const tbody = document.querySelector('#isItemListTable tbody');
        const _this = this;
        if(tbody){
          Sortable.create(tbody, {
            onEnd({newIndex, oldIndex}) {
              const currRow = _this.ruleForm.item_list.splice(oldIndex, 1)[0];
              _this.ruleForm.item_list.splice(newIndex, 0, currRow);
              for (let i = 0; i < _this.ruleForm.item_list.length; i++) {
                _this.$set(_this.ruleForm.item_list[i], 'level', i+1);
              }
            }
          })
        }
      },
      //打开模态框
      openedDialog(id){
        if(!this.isDisabled){
          if(this.options.length){
            this.$nextTick(()=>{
              this.ruleForm.company_id = id
              this.ruleForm.company_id_arr = [id]
            })
          }
        }
        this.rowDrop()
      },
      getRowKeys(row) {
        return row.id;
      },
      // 二级模态框
      //保存二级模态框
      addItemList(){
        let data = {}
        this.$refs.ruleFormItemList.validate(valid =>{
          if(valid){
            if(this.startM == '' || this.startD == '' || this.endM == '' || this.endD == ''){
              this.$message.error('请选择日期')
              return
            }
            if(this.compareDate()){
              this.$message.error('选择日期非法')
              return
            }
            let model = this.$refs.ruleFormItemList.model;
            data.info = model.info;
            data.is_holiday = model.is_holiday;
            data.times = model.times;
            data.start_day = this.startM +'-'+ this.startD;
            data.end_day = this.endM +'-'+ this.endD;
            data.open_time = model.open_time;
            data.close_time = model.close_time;
            data.close_time_next = Number(model.open_time.split(':').join('')) - Number(model.close_time.split(':').join('')) >= 0 ? '次日'+ model.close_time : '';
            data.weeks = model.weeksArr.join(',');
            data.weeksArr = model.weeksArr;
            // console.log(data);
            if(this.ruleFormItmeList.id){
              for(let i in this.ruleForm.item_list){
                if(this.ruleForm.item_list[i].id == this.ruleFormItmeList.id){
                  data.id = this.ruleFormItmeList.id
                  data.level = this.ruleForm.item_list[i].level
                  data.days = [data.start_day,data.end_day]
                  this.ruleForm.item_list[i] = Object.assign(data)
                  this.$set(this.ruleForm.item_list,i,Object.assign(data))
                }
              }
            }else{
              data.id = Math.random().toString(36).substring(2,9);
              data.level = this.ruleForm.item_list.length + 1
              data.days = [data.start_day,data.end_day]
              this.ruleForm.item_list.push(data)
            }
            // console.log(this.ruleForm.item_list,'this.ruleForm.item_list');
            this.isShowItem = false
          }
        })
      },
      // 关闭二级模态框
      closeItemList(){
        this.ruleFormItmeList.id = ''
        this.ItemListId = ''
        this.startM = ''
        this.startD = ''
        this.endM = ''
        this.endD = ''
        this.$refs.ruleFormItemList.resetFields()
      },
      //删除已添加的项目
      itemListDelete(id){
        for(let i in this.ruleForm.item_list){
          if(this.ruleForm.item_list[i].id == id){
            this.ruleForm.item_list.splice(i,1)
          }
        }
        //加入排序
        if (this.ruleForm.item_list && this.ruleForm.item_list.length > 0) {
          for (let i = 0; i < this.ruleForm.item_list.length; i++) {
            this.$set(this.ruleForm.item_list[i], 'level', i+1);
          }
        }
      },
      //绑定区域
      bindArea(data){
        this.bindShow=true;
        this.$Bus.$emit('Loading',true);
        this.$nextTick(()=>{
          this.quyuqiyeId=this.company_id_arr;          
        })
        this.gzTimeName=data.name;
        this.nowTimeId=data.id;
        this.getglArea(data.id);
      },
      //营业时间关联案场列表
      getglArea(id){
        let url='sys/opening_hours/related_area_list?opening_hours_id='+id;
        this.$api.get(url)
        .then(data=>{
          if(data.data){
            this.bindAreaData=data.data;
            for(let i in data.data){
              this.bindAreaData[i].area_id=data.data[i].id;
            }
          }
          else{
            this.bindAreaData=[];
          }
          this.getCase();
          this.$Bus.$emit('Loading',false);
        })
        .catch(err=>{
           console.log(err);
        })
      },
      //案场change
      CaseChange(val){
        //已经选择了全部，想要排除掉all这个选项
        if(val[0] == 'all' && val.length != 1){
          this.submitCase = this.submitCase.filter(x=>x != 'all')
          this.isAllCase = false
        }else if(val.includes('all')){//点击了全部，干掉其他选中的部分
          this.submitCase = ['all'];
          this.isAllCase = true;
        }else{
          this.isAllCase = false
        }
      },
      //案场点击删除
      CasetagClick(){
        if(this.submitCase.length==0) {
          this.$message({
                showClose: true,
                message: '请至少选择一个案场!',
                type: 'warning'
          });

          this.submitCase = ['all'];
          this.isAllCase = true;
        }
        this.getArea();
      },
      CaseVisibleChange(val){
        if (!val){
          if(!this.submitCase.length) {
            this.$message({
                showClose: true,
                message: '请至少选择一个案场!',
                type: 'warning'
            });
            if(this.Case.length)
            {
              this.submitCase = ['all'];
              this.isAllCase = true;
            }
            else{
                return 
            }
          }
          this.getArea();
        }
      },
      getCase(){
        let parmas={
          org_id_list:[this.company_id],
          org_type:1
        }
        let url='/sys/report_assist_new/case_list';
        this.$api.post(url,parmas)
        .then(data=>{
          this.Case = [];
          if(data.data){
            this.Case = data.data;
            this.submitCase = null;
            this.submitCase = [];
            this.Case.unshift({case_name:'全部',id:'all'}); 
            this.submitCase.push('all');
            this.allCaseArr = this.Case.map(x=>{
              return x.id
            });
            this.allCaseArr = this.allCaseArr.filter(x=>{
              return x != 'all'
            });
            this.isAllCase = true;
            this.getArea();
          }
          else{
            this.$message.warning('该企业下无案场');
          }
          this.$Bus.$emit('Loading',false);
        })
        .catch(err=>{
           console.log(err)
          this.$message.warning('该企业下无案场');
          this.Case = [];
          this.submitCase = null;
        })
      },
      //区域列表
      getArea(){
        if(!this.submitCase.length){
          this.$message.warning('请选择案场');
          this.areaData=[];
          return
        }
        
        this.tableLoading=true;
        let org=2;
        let idList=[];
        if(this.isAllCase){
          idList.push(this.company_id);
          org=1;
        }
        else{
          idList=this.submitCase;
        }
        let parmas={
          org_id_list:idList,
          org_type:org
        }
        let url='/sys/report_assist_new/find_area';
        this.$api.post(url,parmas)
        .then(data=>{
          if(data.data)
          {
            this.areaData=data.data;
            this.areaTableCheck=[];
            this.$nextTick(()=>{
              if (this.bindAreaData && this.bindAreaData.length > 0) {
                this.bindAreaData.forEach((ms,msIndex) => {
                  for (let i = 0; i < data.data.length; i++) {
                    const el = data.data[i];
                    if(ms.area_id==el.area_id){
                      this.areaTableCheck.push(el);
                      this.$refs.areaTable.toggleRowSelection(el, true);
                    }
                  }
                });
              };
              this.tableLoading=false;
            })
          }
          else{
            this.$message.warning('该案场下无区域');
            this.areaData=[];
            this.tableLoading=false;
          }
          
        })
        .catch(err=>{
          this.areaData=[];
          this.tableLoading=false;
           console.log(err);
        })
      },
      //移除
      delBind(val){
        this.areaData.forEach((em)=>{
          if(em.area_id==val.area_id){
            this.$refs.areaTable.toggleRowSelection(em,false);
          }
        })
        this.bindAreaData=this.bindAreaData.filter(item=> item.area_id!=val.area_id);
        this.areaTableCheck=this.areaTableCheck.filter(item=> item.area_id!=val.area_id);
      },
      //全部删除
      allDel(){
        this.bindAreaData=[];
        this.areaTableCheck=[];
        this.$refs.areaTable.clearSelection();
      },
      //选择项发生改变
      areaTableSeleteChange(list,row){  
        if(list.length>this.areaTableCheck.length) //选择
        {
          this.bindAreaData.push(row);
        } 
        else{   //取消
          for(let i=0;i<this.bindAreaData.length;i++)
          {
            if(this.bindAreaData[i].area_id==row.area_id){
              this.bindAreaData.splice(i,1);
            }
          }
        }
        this.areaTableCheck=JSON.parse(JSON.stringify(list));
         // list.forEach(item=>{
          //   //在上次选择中查询，未查到则加入
          //   let isAdd=true;
          //   for (let i = 0; i < this.bindAreaData.length; i++) {
          //     const element = this.bindAreaData[i];
          //     if(element.area_id==item.area_id)
          //       isAdd=false
          //   }
          //   if(isAdd) this.bindAreaData.push(item);
         // })
       
      },
      allChange(list){
        if(list.length && this.areaTables.length==this.areaData.length)
        {
          let arrIds=this.bindAreaData.map(item=>item.area_id);
          let newArr=this.areaTables.filter(item=>!arrIds.includes(item.area_id));
          this.bindAreaData=[...this.bindAreaData,...newArr];
          this.areaTableCheck=JSON.parse(JSON.stringify(this.areaData));
        }
        else if(list.length){
           this.bindAreaData=JSON.parse(JSON.stringify(list));
           this.areaTableCheck=JSON.parse(JSON.stringify(list));
        }
        else{
          let qxarrIds=this.areaData.map(item=>item.area_id);
          this.bindAreaData=this.bindAreaData.filter(item=>!qxarrIds.includes(item.area_id));
          this.areaTableCheck=[];
        }
      },
     // //表格禁选
      // checkboxInidt(row,index){
      //   let fan=1;
      //   this.bindAreaData.forEach((em)=>{
      //     if(em.area_id==row.area_id)
      //     {
      //       fan=0
      //     }
      //   })
      //   return fan;
     // },
      //保存
      saveAreaTime(){
        let idarr=this.bindAreaData.length?this.bindAreaData.map(x=>{return x.area_id;}):[];
        this.$Bus.$emit('Loading', true);
        let url='/sys/opening_hours/bind_area?opening_hours_id='+this.nowTimeId;
        this.$api.post(url,idarr)
        .then(data=>{
          if(data.msg=='success'){
            this.bindShow=false;
            this.$Bus.$emit('Loading',false);
            this.$message({
              message: "保存成功",
              type: "success"
            });
          }
          else{
            this.$message({
              message: "保存失败",
              type: "error"
            });
          }
        })
        .catch(err=>{
           console.log(err);
          this.$Bus.$emit('Loading', false);
        })
      },
      //绑定区域模态框关闭
      bindClose(){
        this.nowTimeId='';
        this.gzTimeName='';
        this.areaTableSearch='';
        this.submitCase=[];
        this.Case=[];
        this.quyuqiyeId='';
        this.isAllCase=false;
        this.areaData=[];
        this.bindAreaData=[];
      },
      startMchange(val){
        if(val == '02'){
          this.startDayList = this.DayList3
        }else if(val == '04' || val == '06' || val == '09' || val == '11'){
          this.startDayList = this.DayList2
        }else{
          this.startDayList = this.DayList1
        }
        if(this.startD && !this.startDayList.includes(this.startD)){
          this.startD = ''
        }
      },
      endMchange(val){
        if(val == '02'){
          this.endDayList = this.DayList3
        }else if(val == '04' || val == '06' || val == '09' || val == '11'){
          this.endDayList = this.DayList2
        }else{
          this.endDayList = this.DayList1
        }
        if(this.endD && !this.endDayList.includes(this.endD)){
          this.endD = ''
        }
      },
      compareDate(){
        let startM = Number(this.startM)
        let startD = Number(this.startD)
        let endM = Number(this.endM)
        let endD = Number(this.endD)

        if(startM > endM){
          return true
        }else if(startM == endM){
          if(startD > endD){
            return true
          }else{
            return false
          }
        }

        return false
      }
    }
  }
</script>

<style lang="scss">
  .bindareadia{
    .el-dialog{
      .el-dialog__body{
        &::after,&::before{
          content:'';
          display:block;
          clear:both;
        }
       // .el-table.areaT{
        //   .el-table__header-wrapper{
        //     .el-table__header{
        //       th{
        //         overflow: initial;
        //       }
        //     }
            
        //     .cell{
        //       overflow: initial;
        //       &:hover{
        //         .el-checkbox{
        //           .el-checkbox__input{
        //             &::after{
        //                color:#6689f1;
        //             }
        //           }
        //         }
        //       }
        //       .el-checkbox{
        //         position: absolute;
        //         left: 8%;
        //         top: 50%;
        //         transform: translateY(-50%);
        //         .el-checkbox__input{
        //           &::after{
        //             content: '全选';
        //             position: absolute;
        //             left: 115%;
        //             font-size: 12px;
        //             color:#606266;
        //           }
        //           .el-checkbox__inner{
        //             background-color: #6689f1;
        //             border-color: #6689f1;
        //             &::before,&::after{
        //               box-sizing: content-box;
        //               content: "";
        //               border: 1px solid #FFF;
        //               transform: rotate(45deg) scaleY(1);
        //               background-color:transparent;
        //               width: 3px;
        //               transform-origin: center;
        //               border-left: 0;
        //               border-top: 0;
        //               height: 7px;
        //               left: 4px;
        //               position: absolute;
        //               top: 1px;
        //             }
        //           }
        //         }
        //       }
        //     }
        //   }
        //   .el-table__body-wrapper{
        //     .el-table__row{
        //       .cell{
                
        //         .el-checkbox__input.is-disabled,.el-checkbox__input.is-checked{
        //           .el-checkbox__inner{
                    
        //             &::after{
        //               border-color:#6689f1;
        //               transform: rotate(45deg) scaleY(1);
        //             }
        //           }
        //         }
        //       }
        //     }
        //   }
       // }
      }
    }
  }
  .areasearch-Box{
    float: right;
    line-height: 30px;
    height: 30px;
    span{
      display: block;
      cursor: pointer;
      -webkit-touch-callout: none;
      /*禁止复制*/
      -webkit-user-select: none;
      -khtml-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
      &:hover{
        color:#85a1f4;
      }
    }  
    .table-search{
      .el-input__inner{
            line-height: 30px;
        height: 30px;
      }
      .el-input__icon{
        line-height: 30px;
      }
    }
  }
  .page-content {
    padding: 15px;

    .fr {
      float: right;
    }

    .el-table {
      margin-bottom: 10px;
    }

    .paging {
      margin: 15px;
      height: 28px;
    }
  }
  
  
</style>